package com.tencent.bugly.crashreport.crash.anr;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.os.FileObserver;
import android.os.Process;
import com.google.android.exoplayer2.DefaultRenderersFactory;
import com.tencent.bugly.BuglyStrategy;
import com.tencent.bugly.crashreport.common.strategy.StrategyBean;
import com.tencent.bugly.crashreport.crash.CrashDetailBean;
import com.tencent.bugly.crashreport.crash.anr.TraceFileHelper;
import com.tencent.bugly.crashreport.crash.c;
import com.tencent.bugly.proguard.ae;
import com.tencent.bugly.proguard.am;
import com.tencent.bugly.proguard.an;
import com.tencent.bugly.proguard.ap;
import com.tencent.bugly.proguard.aq;
import com.tencent.bugly.proguard.as;
import com.tencent.bugly.proguard.at;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/* compiled from: BUGLY */
/* loaded from: classes.dex */
public class b implements at {
    private final Context c;
    private final com.tencent.bugly.crashreport.common.info.a d;
    private final am e;
    private final com.tencent.bugly.crashreport.common.strategy.a f;
    private final String g;
    private final com.tencent.bugly.crashreport.crash.b h;
    private FileObserver i;
    private AtomicInteger a = new AtomicInteger(0);
    private long b = -1;
    private boolean j = true;

    public b(Context context, com.tencent.bugly.crashreport.common.strategy.a aVar, com.tencent.bugly.crashreport.common.info.a aVar2, am amVar, ae aeVar, com.tencent.bugly.crashreport.crash.b bVar, BuglyStrategy.a aVar3) {
        this.c = aq.a(context);
        this.g = context.getDir("bugly", 0).getAbsolutePath();
        this.d = aVar2;
        this.e = amVar;
        this.f = aVar;
        this.h = bVar;
    }

    protected ActivityManager.ProcessErrorStateInfo a(Context context, long j) {
        if (j < 0) {
            j = 0;
        }
        try {
            an.c("to find!", new Object[0]);
            ActivityManager activityManager = (ActivityManager) context.getSystemService("activity");
            long j2 = j / 500;
            int i = 0;
            while (true) {
                an.c("waiting!", new Object[0]);
                List<ActivityManager.ProcessErrorStateInfo> processesInErrorState = activityManager.getProcessesInErrorState();
                if (processesInErrorState != null) {
                    for (ActivityManager.ProcessErrorStateInfo processErrorStateInfo : processesInErrorState) {
                        if (processErrorStateInfo.condition == 2) {
                            an.c("found!", new Object[0]);
                            return processErrorStateInfo;
                        }
                    }
                }
                aq.b(500L);
                int i2 = i + 1;
                if (i >= j2) {
                    an.c("end!", new Object[0]);
                    return null;
                }
                i = i2;
            }
        } catch (Exception e) {
            an.b(e);
            return null;
        }
    }

    protected a a(Context context, ActivityManager.ProcessErrorStateInfo processErrorStateInfo, long j, Map<String, String> map) {
        File filesDir = context.getFilesDir();
        File file = new File(filesDir, "bugly/bugly_trace_" + j + ".txt");
        a aVar = new a();
        aVar.c = j;
        aVar.d = file.getAbsolutePath();
        aVar.a = processErrorStateInfo != null ? processErrorStateInfo.processName : "";
        aVar.f = processErrorStateInfo != null ? processErrorStateInfo.shortMsg : "";
        aVar.e = processErrorStateInfo != null ? processErrorStateInfo.longMsg : "";
        aVar.b = map;
        if (map != null) {
            for (String str : map.keySet()) {
                if (str.startsWith("main(")) {
                    aVar.g = map.get(str);
                }
            }
        }
        Object[] objArr = new Object[6];
        objArr[0] = Long.valueOf(aVar.c);
        objArr[1] = aVar.d;
        objArr[2] = aVar.a;
        objArr[3] = aVar.f;
        objArr[4] = aVar.e;
        objArr[5] = Integer.valueOf(aVar.b != null ? aVar.b.size() : 0);
        an.c("anr tm:%d\ntr:%s\nproc:%s\nsMsg:%s\n lMsg:%s\n threads:%d", objArr);
        return aVar;
    }

    protected CrashDetailBean a(a aVar) {
        CrashDetailBean crashDetailBean = new CrashDetailBean();
        try {
            crashDetailBean.C = com.tencent.bugly.crashreport.common.info.b.i();
            crashDetailBean.D = com.tencent.bugly.crashreport.common.info.b.g();
            crashDetailBean.E = com.tencent.bugly.crashreport.common.info.b.k();
            crashDetailBean.F = this.d.p();
            crashDetailBean.G = this.d.o();
            crashDetailBean.H = this.d.q();
            crashDetailBean.w = aq.a(this.c, c.e, c.h);
            crashDetailBean.b = 3;
            crashDetailBean.e = this.d.h();
            crashDetailBean.f = this.d.p;
            crashDetailBean.g = this.d.w();
            crashDetailBean.m = this.d.g();
            crashDetailBean.n = "ANR_EXCEPTION";
            crashDetailBean.o = aVar.f;
            crashDetailBean.q = aVar.g;
            crashDetailBean.P = new HashMap();
            crashDetailBean.P.put("BUGLY_CR_01", aVar.e);
            int indexOf = crashDetailBean.q != null ? crashDetailBean.q.indexOf("\n") : -1;
            crashDetailBean.p = indexOf > 0 ? crashDetailBean.q.substring(0, indexOf) : "GET_FAIL";
            crashDetailBean.r = aVar.c;
            if (crashDetailBean.q != null) {
                crashDetailBean.u = aq.b(crashDetailBean.q.getBytes());
            }
            crashDetailBean.z = aVar.b;
            crashDetailBean.A = aVar.a;
            crashDetailBean.B = "main(1)";
            crashDetailBean.I = this.d.y();
            crashDetailBean.h = this.d.v();
            crashDetailBean.i = this.d.J();
            crashDetailBean.v = aVar.d;
            crashDetailBean.M = this.d.t;
            crashDetailBean.N = this.d.a;
            crashDetailBean.O = this.d.a();
            crashDetailBean.Q = this.d.H();
            crashDetailBean.R = this.d.I();
            crashDetailBean.S = this.d.B();
            crashDetailBean.T = this.d.G();
            this.h.c(crashDetailBean);
            crashDetailBean.y = ap.a();
        } catch (Throwable th) {
            if (!an.a(th)) {
                th.printStackTrace();
            }
        }
        return crashDetailBean;
    }

    protected boolean a(String str, String str2, String str3) {
        BufferedWriter bufferedWriter;
        TraceFileHelper.a readTargetDumpInfo = TraceFileHelper.readTargetDumpInfo(str3, str, true);
        if (readTargetDumpInfo == null || readTargetDumpInfo.d == null || readTargetDumpInfo.d.size() <= 0) {
            an.e("not found trace dump for %s", str3);
            return false;
        }
        File file = new File(str2);
        try {
            if (!file.exists()) {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();
            }
            if (!file.exists() || !file.canWrite()) {
                an.e("backup file create fail %s", str2);
                return false;
            }
            BufferedWriter bufferedWriter2 = null;
            try {
                try {
                    bufferedWriter = new BufferedWriter(new FileWriter(file, false));
                    try {
                        String[] strArr = readTargetDumpInfo.d.get("main");
                        int i = 3;
                        if (strArr != null && strArr.length >= 3) {
                            String str4 = strArr[0];
                            String str5 = strArr[1];
                            String str6 = strArr[2];
                            bufferedWriter.write("\"main\" tid=" + str6 + " :\n" + str4 + "\n" + str5 + "\n\n");
                            bufferedWriter.flush();
                        }
                        for (Map.Entry<String, String[]> entry : readTargetDumpInfo.d.entrySet()) {
                            if (!entry.getKey().equals("main")) {
                                if (entry.getValue() != null && entry.getValue().length >= i) {
                                    String str7 = entry.getValue()[0];
                                    String str8 = entry.getValue()[1];
                                    String str9 = entry.getValue()[2];
                                    bufferedWriter.write("\"" + entry.getKey() + "\" tid=" + str9 + " :\n" + str7 + "\n" + str8 + "\n\n");
                                    bufferedWriter.flush();
                                }
                                i = 3;
                            }
                        }
                        try {
                            bufferedWriter.close();
                        } catch (IOException e) {
                            if (!an.a(e)) {
                                e.printStackTrace();
                            }
                        }
                        return true;
                    } catch (IOException e2) {
                        e = e2;
                        bufferedWriter2 = bufferedWriter;
                        if (!an.a(e)) {
                            e.printStackTrace();
                        }
                        an.e("dump trace fail %s", e.getClass().getName() + ":" + e.getMessage());
                        if (bufferedWriter2 != null) {
                            try {
                                bufferedWriter2.close();
                            } catch (IOException e3) {
                                if (!an.a(e3)) {
                                    e3.printStackTrace();
                                }
                            }
                        }
                        return false;
                    } catch (Throwable th) {
                        th = th;
                        Throwable th2 = th;
                        if (bufferedWriter != null) {
                            try {
                                bufferedWriter.close();
                            } catch (IOException e4) {
                                if (!an.a(e4)) {
                                    e4.printStackTrace();
                                }
                            }
                        }
                        throw th2;
                    }
                } catch (Throwable th3) {
                    th = th3;
                    bufferedWriter = bufferedWriter2;
                }
            } catch (IOException e5) {
                e = e5;
            }
        } catch (Exception e6) {
            if (!an.a(e6)) {
                e6.printStackTrace();
            }
            an.e("backup file create error! %s  %s", e6.getClass().getName() + ":" + e6.getMessage(), str2);
            return false;
        }
    }

    public boolean a() {
        return this.a.get() != 0;
    }

    public boolean a(Context context, String str, ActivityManager.ProcessErrorStateInfo processErrorStateInfo, long j, Map<String, String> map) {
        a a = a(context, processErrorStateInfo, j, map);
        if (!this.f.b()) {
            an.e("crash report sync remote fail, will not upload to Bugly , print local for helpful!", new Object[0]);
            com.tencent.bugly.crashreport.crash.b.a("ANR", aq.a(), a.a, "main", a.e, null);
            return false;
        } else if (!this.f.c().j) {
            an.d("ANR Report is closed!", new Object[0]);
            return false;
        } else {
            an.a("found visiable anr , start to upload!", new Object[0]);
            CrashDetailBean a2 = a(a);
            if (a2 == null) {
                an.e("pack anr fail!", new Object[0]);
                return false;
            }
            c.a().a(a2);
            if (a2.a >= 0) {
                an.a("backup anr record success!", new Object[0]);
            } else {
                an.d("backup anr record fail!", new Object[0]);
            }
            if (str != null && new File(str).exists()) {
                this.a.set(3);
                if (a(str, a.d, a.a)) {
                    an.a("backup trace success", new Object[0]);
                }
            }
            com.tencent.bugly.crashreport.crash.b.a("ANR", aq.a(), a.a, "main", a.e, a2);
            if (!this.h.a(a2)) {
                this.h.a(a2, 3000L, true);
            }
            this.h.b(a2);
            return true;
        }
    }

    public final void a(String str) {
        long j;
        synchronized (this) {
            if (this.a.get() != 0) {
                an.c("trace started return ", new Object[0]);
                return;
            }
            this.a.set(1);
            try {
                an.c("read trace first dump for create time!", new Object[0]);
                TraceFileHelper.a readFirstDumpInfo = TraceFileHelper.readFirstDumpInfo(str, false);
                long j2 = readFirstDumpInfo != null ? readFirstDumpInfo.c : -1L;
                if (j2 == -1) {
                    an.d("trace dump fail could not get time!", new Object[0]);
                    j2 = System.currentTimeMillis();
                }
                j = j2;
            } finally {
                try {
                    return;
                } finally {
                }
            }
            if (Math.abs(j - this.b) < 10000) {
                an.d("should not process ANR too Fre in %d", 10000);
            } else {
                this.b = j;
                this.a.set(1);
                Map<String, String> a = aq.a(c.f, false);
                if (a != null && a.size() > 0) {
                    ActivityManager.ProcessErrorStateInfo a2 = a(this.c, 10000L);
                    if (a2 == null) {
                        an.c("proc state is unvisiable!", new Object[0]);
                    } else if (a2.pid == Process.myPid()) {
                        an.a("found visiable anr , start to process!", new Object[0]);
                        a(this.c, str, a2, j, a);
                        return;
                    } else {
                        an.c("not mind proc!", a2.processName);
                    }
                }
                an.d("can't get all thread skip this anr", new Object[0]);
            }
        }
    }

    protected synchronized void b() {
        if (d()) {
            an.d("start when started!", new Object[0]);
            return;
        }
        this.i = new FileObserver("/data/anr/", 8) { // from class: com.tencent.bugly.crashreport.crash.anr.b.1
            @Override // android.os.FileObserver
            public void onEvent(int i, String str) {
                if (str == null) {
                    return;
                }
                String str2 = "/data/anr/" + str;
                if (!str2.contains("trace")) {
                    an.d("not anr file %s", str2);
                } else {
                    b.this.a(str2);
                }
            }
        };
        this.i.startWatching();
        an.a("start anr monitor!", new Object[0]);
        this.e.a(new Runnable() { // from class: com.tencent.bugly.crashreport.crash.anr.b.2
            @Override // java.lang.Runnable
            public void run() {
                b.this.f();
            }
        });
    }

    protected synchronized void c() {
        if (!d()) {
            an.d("close when closed!", new Object[0]);
            return;
        }
        this.i.stopWatching();
        this.i = null;
        an.d("close anr monitor!", new Object[0]);
    }

    protected synchronized boolean d() {
        return this.i != null;
    }

    protected synchronized void a(boolean z) {
        if (z) {
            b();
        } else {
            c();
        }
    }

    public synchronized boolean e() {
        return this.j;
    }

    private synchronized void c(boolean z) {
        if (this.j != z) {
            an.a("user change anr %b", Boolean.valueOf(z));
            this.j = z;
        }
    }

    public void b(boolean z) {
        c(z);
        boolean e = e();
        com.tencent.bugly.crashreport.common.strategy.a a = com.tencent.bugly.crashreport.common.strategy.a.a();
        if (a != null) {
            e = e && a.c().g;
        }
        if (e != d()) {
            an.a("anr changed to %b", Boolean.valueOf(e));
            a(e);
        }
    }

    protected void f() {
        int indexOf;
        long b = aq.b() - c.g;
        File file = new File(this.g);
        if (file.exists() && file.isDirectory()) {
            try {
                File[] listFiles = file.listFiles();
                if (listFiles != null && listFiles.length != 0) {
                    int i = 0;
                    for (File file2 : listFiles) {
                        String name = file2.getName();
                        if (name.startsWith("bugly_trace_") && (((indexOf = name.indexOf(".txt")) <= 0 || Long.parseLong(name.substring(12, indexOf)) < b) && file2.delete())) {
                            i++;
                        }
                    }
                    an.c("Number of overdue trace files that has deleted: " + i, new Object[0]);
                }
            } catch (Throwable th) {
                an.a(th);
            }
        }
    }

    public synchronized void a(StrategyBean strategyBean) {
        if (strategyBean == null) {
            return;
        }
        if (strategyBean.j != d()) {
            an.d("server anr changed to %b", Boolean.valueOf(strategyBean.j));
        }
        if (Build.VERSION.SDK_INT <= 19) {
            boolean z = strategyBean.j && e();
            if (z != d()) {
                an.a("anr changed to %b", Boolean.valueOf(z));
                a(z);
            }
        } else if (strategyBean.j) {
            h();
        } else {
            i();
        }
    }

    public void g() {
        int i = 0;
        while (true) {
            int i2 = i + 1;
            if (i >= 30) {
                return;
            }
            try {
                an.a("try main sleep for make a test anr! try:%d/30 , kill it if you don't want to wait!", Integer.valueOf(i2));
                aq.b((long) DefaultRenderersFactory.DEFAULT_ALLOWED_VIDEO_JOINING_TIME_MS);
                i = i2;
            } catch (Throwable th) {
                if (an.a(th)) {
                    return;
                }
                th.printStackTrace();
                return;
            }
        }
    }

    @Override // com.tencent.bugly.proguard.at
    public boolean a(Thread thread) {
        new HashMap();
        if (thread.getName().contains("main")) {
            ActivityManager.ProcessErrorStateInfo a = a(this.c, 10000L);
            if (a == null) {
                an.c("anr handler onThreadBlock proc state is unvisiable!", new Object[0]);
                return false;
            } else if (a.pid != Process.myPid()) {
                an.c("onThreadBlock not mind proc!", a.processName);
                return false;
            } else {
                try {
                    Map<String, String> a2 = aq.a(200000, false);
                    an.a("onThreadBlock found visiable anr , start to process!", new Object[0]);
                    a(this.c, "", a, System.currentTimeMillis(), a2);
                } catch (Throwable unused) {
                    return false;
                }
            }
        } else {
            an.c("anr handler onThreadBlock only care main thread", new Object[0]);
        }
        return true;
    }

    public void h() {
        as.a(this.c).a();
        as.a(this.c).a(this);
        as.a(this.c).d();
    }

    public void i() {
        as.a(this.c).b();
        as.a(this.c).b(this);
        as.a(this.c).c();
    }
}
